import { Link, useLocation, useNavigate } from 'react-router-dom';
import styles from "./UpdateRegionTypes.module.scss";
import { useForm } from 'react-hook-form';
import { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';

import exclamation from './../../../images/exclamation.svg';
import { ROUTES } from '../../../utils/conts';
import Button from '../../UI/button/Button';
import { updateUser } from '../../../features/account/account';
import { getCookie } from '../../../utils';
import { createRegionTypes, updateRegionTypesById } from '../../../features/regionTypes/regionTypes';

const UpdateRegionTypes = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);

  const myCookieValueUserId = getCookie('id');
  const {
    register,
    reset,
    formState: { errors, isValid },
    handleSubmit,
  } = useForm({
    mode: 'onBlur',
  });
  const [err, setErr] = useState('');

  const onSubmit = (data) => {
    console.log(data);
    setIsLoading(true);
    if (data.types === '') {
      setErr('Заполните все поля');
      return;
    }

    // const updateTypes = {
    //   typeId:  фаы,
    //   body: data
    // }

    dispatch(updateRegionTypesById(data)).then((response) => {
      setIsLoading(true);
      setErr('');
      if (response.payload?.response?.status === 401) {
        setErr(response.payload.response.data);
        setIsLoading(false);
        reset();
      }

      if (
        response.payload?.response?.status === 409 ||
        response.payload?.response?.status === 400
      ) {
        setErr(response.payload.response.data);
        setIsLoading(false);
        reset();
      }

      if (response.payload?.status === 201) {
        navigate(ROUTES.TYPES__REGION);
      }
    });
  };

  return (
    <section className={styles.signUp}>
      <div className={styles.wrapper}>
        <div className={styles.title}>
          <h1>Укажите тип региона</h1>
        </div>
        <p className={styles.err}>{err}</p>
        <form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
          <div className={styles.group}>
            <label>
              <h3>Имя</h3>
              <input
                {...register('type', {
                  required: 'Поля обязательное к заполнению',
                })}
              />
              {errors?.firstName && (
                <div className={styles.exclamation}>
                  <img src={exclamation} />
                  <p>{errors.firstName.message}</p>
                </div>
              )}
            </label>
          </div>
          <Button disabled={!isValid || isLoading} styleWidth={styles.buttonWidth}>
            Создать
          </Button>
        </form>
      </div>
    </section>
  );
};

export default UpdateRegionTypes;
